package com.spzx.product.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.redis.annotation.XingXingCache;
import com.spzx.product.api.domain.vo.CategoryVo;
import com.spzx.product.domain.Category;
import com.spzx.product.domain.vo.CategoryExcelVo;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.CategoryService;
import com.spzx.product.utils.CategoryUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName CategoryServiceImpl
 * @Author 波
 * @Date 2024/7/29 18:44
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    /**
     * 根据ID查询商品分类信息的列表
     *
     * @param id 传入的商品分类ID
     * @return 商品分类信息的列表
     */
    @Override
    public List<Category> getCategoryById(Long id) {
        List<Category> categoryList = categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, id));
        if (!CollectionUtils.isEmpty(categoryList)) {
            for (Category category : categoryList) {
                Long count = categoryMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, category.getId()));
                if (count > 0) {
                    category.setHasChildren(true);
                } else {
                    category.setHasChildren(false);
                }
            }
        }

        return categoryList;
    }

    @Override
    public List<Long> getAllCategoryIdList(Long category3Id) {
        ArrayList<Long> categoryArrayList = new ArrayList<>();
        List<Category> categoryList = this.getParentCategory(category3Id, new ArrayList<Category>());
        for (int i = categoryList.size(); i > 0; i--) {
            categoryArrayList.add(categoryList.get(i - 1).getId());

        }
        return categoryArrayList;
    }

    public List<Category> getParentCategory(Long category3Id, ArrayList<Category> categoryList) {
        if (category3Id.intValue() > 0) {
            Category category = categoryMapper.selectOne(new LambdaQueryWrapper<Category>().eq(Category::getId, category3Id));
            categoryList.add(category);
            return getParentCategory(category.getParentId(), categoryList);
        }
        return categoryList;
    }

    /**
     * 文件导出
     *
     * @param response
     */
    @SneakyThrows
    @Override
    public void download(HttpServletResponse response) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("分类数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
        List<Category> categoryList = baseMapper.selectList(null);
        List<CategoryExcelVo> categoryExcelVoList = categoryList.stream().map(category -> {
            CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
            BeanUtils.copyProperties(category, categoryExcelVo);
            return categoryExcelVo;
        }).collect(Collectors.toList());

        EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).sheet("分类数据").doWrite(categoryExcelVoList);
    }

    /**
     * 文件导入
     *
     * @param file
     */
    @SneakyThrows
    @Override
    public void upload(MultipartFile file) {
        List<CategoryExcelVo> categoryExcelVoList = EasyExcel.read(file.getInputStream()).head(CategoryExcelVo.class).sheet().doReadSync();
        if (!CollectionUtils.isEmpty(categoryExcelVoList)) {
            List<Category> categoryList = categoryExcelVoList.stream().map(categoryExcelVo -> {
                Category category = new Category();
                BeanUtils.copyProperties(categoryExcelVo, category);
                return category;
            }).collect(Collectors.toList());
            this.saveBatch(categoryList);
        }
    }


    /**
     * 查询一级分类列表
     * @return List<CategoryVo>
     */
    @Override
    @XingXingCache(prefix = "product:category:one")
    public List<CategoryVo> getOneCategory() {
        List<Category> categoryList = categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, 0));
        List<CategoryVo> categoryVoList = categoryList.stream().map(category -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());
        return categoryVoList;
    }

    /**
     * 查询所有分类信息
     * @return List<CategoryVo>
     */
    @Override
    @XingXingCache(prefix = "product:category:tree")
    public List<CategoryVo> getCategoryTree() {
        List<Category> categoryList = categoryMapper.selectList(null);
        List<CategoryVo> categoryVoList = categoryList.stream().map(category -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());

        return CategoryUtils.buildTree(categoryVoList);
    }


}
